﻿using System;
using System.Windows.Automation;
using QuickUIT.Utilities;

namespace QuickUIT
{
    /// <summary>
    /// Matches an <see cref="AutomationProperty"/> on a <see cref="AutomationElement"/> by determining if it contains a specified <see cref="String"/> value.
    /// </summary>
    public class AutomationElementContainsSearchCondition : IAutomationElementSearchCondition
    {
        /// <summary>
        /// Gets the property to be matched. 
        /// </summary>
        public AutomationProperty Property
        {
            get { return _property; } 
        }
        
        /// <summary>
        /// Gets the value to look for in the property. 
        /// </summary>
        public object Value
        {
            get { return _value; } 
        }

        private readonly AutomationProperty _property; 
        private readonly string _value; 

        /// <summary>
        /// Creates a new search condition which matches a property by determining if it contains a specified <see cref="String"/> value. 
        /// </summary>
        /// <param name="property">The property to match.</param>
        /// <param name="value">The value to match the property by.</param>
        public AutomationElementContainsSearchCondition(AutomationProperty property, string value)
        {
            ValidationUtility.ValidateArgumentNotNull(property, "property");
            _property = property;
            _value = value ?? String.Empty; 
        }

        /// <summary>
        /// Indicates whether an <see cref="AutomationElement"/> matches the search condition.  
        /// </summary>
        /// <param name="element">The element to check.</param>
        /// <returns>True if the search condition matches a property on the element; otherwise, false.</returns>
        public bool Matches(AutomationElement element)
        {
            object rawValue = element.GetCurrentPropertyValue(_property);
            string currentValue = rawValue != null ? rawValue.ToString() : String.Empty;
            return currentValue.Contains(_value); 
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            string property = Property.ProgrammaticName.Split('.')[1];
            string value = Value != null ? Value.ToString() : String.Empty;
            return String.Format("{0}=Contains('{1}')", property.Replace("Property", String.Empty), value);
        }
    }
}
